package com.zuiacsn.forum.controller;

import com.zuiacsn.forum.common.AppResult;
import com.zuiacsn.forum.common.ResultCode;
import com.zuiacsn.forum.config.AppConfig;
import com.zuiacsn.forum.dao.MessageMapper;
import com.zuiacsn.forum.model.Message;
import com.zuiacsn.forum.model.User;
import com.zuiacsn.forum.service.IMessageService;
import com.zuiacsn.forum.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;


@Api(tags = "站内信相关接口")
@RestController
@RequestMapping("/message")
@Slf4j
public class MessageController {

    @Autowired
    IMessageService messageService;
    @Autowired
    IUserService userService;
    @Autowired
    private MessageMapper messageMapper;

    @ApiOperation("发送站内信")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @ApiParam("板块id") @Param("id") @NonNull Long receiveUserId,
                          @ApiParam("板块id") @Param("id") @NonNull String content){
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        // 判断用户是否禁言
        if(user == null || user.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        // 不能给自己发送站内信
        if(user.getId() == receiveUserId){
            return AppResult.failed(ResultCode.FAILED);
        }

        // 判断接收者是否存在
        User receiveUser = userService.selectById(receiveUserId);
        if(receiveUser == null){
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        // 调用service方法
        Message message = new Message();
        message.setContent(content);
        message.setReceiveUserId(receiveUserId);
        message.setPostUserId(user.getId());
        messageService.create(message);

        // 返回结果
        return AppResult.success();
    }

    @GetMapping("/getUnreadCount")
    @ApiOperation("获取未读站内信个数")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request){
        // 获取当前登录的用户信息
        User user = (User)request.getSession().getAttribute(AppConfig.USER_SESSION);
        int count = messageService.selectUnreadCount(user.getId());
        return AppResult.success(count);
    }


    @GetMapping("/getAll")
    @ApiOperation("获取站内信列表")
    public AppResult<List<Message>> getAll(HttpServletRequest request){
        User user = (User)request.getSession(false).getAttribute(AppConfig.USER_SESSION);
        List<Message> messages = messageService.selectByReceiveUserId(user.getId());
        return AppResult.success(messages);
    }

    @PostMapping("/markRead")
    @ApiOperation("更新站内信已读状态")
    public AppResult markRead( @ApiParam("站内信id") @Param("id") @NonNull Long id){
        messageService.updateStateById(id, (byte) 1);
        return AppResult.success();
    }


    /**
     * 回复站内信
     * @param repliedId 要回复的站内信Id
     * @param content 站内信的内容
     * @return AppResult
     */
    @ApiOperation("回复站内信")
    @PostMapping("/reply")
    public AppResult reply (HttpServletRequest request,
                            @ApiParam("要回复的站内信Id") @RequestParam("repliedId") @NonNull Long repliedId,
                            @ApiParam("站内信的内容") @RequestParam("content") @NonNull String content) {
        // 校验当前登录用户的状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        // 校验要回复的站内信状态
        Message existsMessage = messageService.selectById(repliedId);
        if (existsMessage == null || existsMessage.getDeleteState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        // 不能给自己回复
        if (user.getId() == existsMessage.getPostUserId()) {
            // 返回错误描述
            return AppResult.failed("不能回复自己的站内信");
        }
        // 构造对象
        Message message = new Message();
        message.setPostUserId(user.getId()); // 发送者
        message.setReceiveUserId(existsMessage.getPostUserId()); // 接收者
        message.setContent(content); // 内容
        // 调用Service
        messageService.reply(repliedId, message);
        // 返回结果
        return AppResult.success();
    }

}
